package com.qys.livesMall.app.user.utils;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import com.qys.livesMall.app.user.constants.RedisConstant;
import com.qys.livesMall.app.user.enums.SmsEnum;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.system.service.IH2SysConfigService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 *
 * 注意：使用heysky渠道发送短信时，需要根据不同服务器选择不同的api
 * @author yxh
 */
@Slf4j
@Component
public class SmsUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * heysky短信，
     * 国外服务器使用 api2.santo.cc
     * 国内服务器使用 api.santo.cc
     */
    private static final String url = "https://api.santo.cc/submit";
    private static final String APP_KEY = "Rss7R7qG";
    private static final String APP_SECRET = "0MLgrnez";

    /**
     * 腾讯云短信
     */
    private static final String TEMPLATEID_ID = "1950719"; //短信模板id
    private static final String APP_ID = "1400860832";
    private static final String YUN_API_KEY = "AKID32scGlBSbblmojUHtZFrhbMy1xhEbprf";
    private static final String YUN_API_SECRET = "g8RYSCyYR7ZqwscHm35vb5OXTxDH8nJf";


    /**
     * 短信调用渠道key(指定供应商)
     */
    private static final String CHANNEL_KEY = "d512b57a6dd54f80a6885f1ccd217c28";
    private static final String HEYSKY_CHANNEL = "heysky";
    private static final String TENCENT_CHANNEL = "tencent";

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        SmsUtil.applicationContext = applicationContext;
    }

    /**
     * 根据业务发送短信
     * @param phoneNumber 电话，例 8613988889999
     * @param type        业务类型
     * @return
     */
    public static boolean sendMessage(String phoneNumber, SmsEnum type) {

        //格式化处理
        phoneNumber = formattedNumber(phoneNumber);

        RedisCache redisCache = applicationContext.getBean(RedisCache.class);
        IH2SysConfigService sysConfigService = applicationContext.getBean(IH2SysConfigService.class);

        //当前时间
        long now = Instant.now().getEpochSecond();

        //请求是否超过一分钟
        String code = redisCache.getCacheObject(RedisConstant.SMS + type.getCode() + ":" + phoneNumber);
        if(StringUtils.isNotEmpty(code)){
            long time = Long.parseLong(code.split(":")[1]);
            if(now < time + 60){
                return false;
            }
        }

        // 最小值为100000（六位数的最小值）
        int min = 100000;
        // 最大值为999999（六位数的最大值）
        int max = 999999;
        // 生成一个六位的随机整数
        int randomNumber = new Random().nextInt(max - min + 1) + min;

        //发送短信
        String msg = String.format(MessageUtils.message(type.getTemplate()), randomNumber);

        //选择供应商
        String messageChannel = sysConfigService.getConfigKey(CHANNEL_KEY);

        boolean result = false;
        if(HEYSKY_CHANNEL.equals(messageChannel)){
            result = sendSms(phoneNumber, msg);
        } else if (TENCENT_CHANNEL.equals(messageChannel)) {
            result = sendSmsByTencent(phoneNumber, String.valueOf(randomNumber));
        }

        if(result){
            redisCache.setCacheObject(RedisConstant.SMS + type.getCode() + ":" + phoneNumber, randomNumber + ":" + now, 5L, TimeUnit.MINUTES);
            return true;
        }
        return false;
    }

    /**
     * 腾讯云渠道发送短信
     * @param phoneNumber  电话，例 8613988889999
     * @param randomNumber 验证码
     * https://cloud.tencent.com/document/api/382/55981
     * @return
     */
    private static boolean sendSmsByTencent(String phoneNumber, String randomNumber) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(YUN_API_KEY, YUN_API_SECRET);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            req.setPhoneNumberSet(new String[]{"+" + phoneNumber});
            req.setSmsSdkAppId(APP_ID);
            req.setTemplateId(TEMPLATEID_ID);
            req.setTemplateParamSet(new String[]{randomNumber});

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);

            SendStatus[] statusSet = resp.getSendStatusSet();
            if(statusSet != null){
                SendStatus sendStatus = statusSet[0];
                if ("Ok".equals(sendStatus.getCode())) {
                    log.info("腾讯云短信发送成功");
                    return true;
                } else {
                    log.info("腾讯云短信发送失败，返回结果{}", JSONObject.toJSONString(resp));
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("腾讯云短信发送异常", e);
        }
        return false;
    }

    /**
     * heysky渠道短信发送
     *
     * @param mobile  电话，例 8613988889999
     * @param message 消息
     * https://heysky.oss-cn-hangzhou.aliyuncs.com/api/santoapi_v301.pdf
     */
    public static boolean sendSms(String mobile, String message) {

        Map<String, Object> param = Maps.newHashMap();
        param.put("command", "MT_REQUEST");
        param.put("cpid", APP_KEY);
        param.put("cppwd", APP_SECRET);
        param.put("da", mobile);
        param.put("sm", message);

        try {
            String result = HttpUtil.get(url, param);
            if(result.contains("ACCEPT")){
                log.info("heysky短信发送成功");
                return true;
            } else {
                log.info("heysky短信发送失败，返回结果{}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("heysky短信发送异常", e);
            return false;
        }
    }


    /**
     * 校验验证码是否正确
     * @param type  业务类型
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    public static boolean verifyCode(SmsEnum type, String phone, String code){

        if("666665".equals(code)){
            return true;
        }

        if(StringUtils.isNotBlank(code)){
            RedisCache redisCache = applicationContext.getBean(RedisCache.class);
            //短信验证码校验
            String codeByCache = redisCache.getCacheObject(RedisConstant.SMS + type.getCode() + ":" + formattedNumber(phone));
            if(StringUtils.isEmpty(codeByCache)){
                throw new QysException(MessageUtils.message("code.error"));
            } else {
                if(!code.equals(codeByCache.split(":")[0])){
                    throw new QysException(MessageUtils.message("code.error"));
                } else {
                    return Boolean.TRUE;
                }
            }
        } else {
            return Boolean.FALSE;
        }
    }


    /**
     * 格式化手机号，去除符号
     * @param oldNumber 原始手机号
     * @return  新手机号
     */
    private static String formattedNumber(String oldNumber){
        return oldNumber.replace("+", "").replace("-", "");
    }

}
